package com.demo.personalaccountingbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.personalaccountingbackend.dto.ApiResponse;
import com.demo.personalaccountingbackend.entity.Category;
import com.demo.personalaccountingbackend.mapper.CategoryMapper;
import com.demo.personalaccountingbackend.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类描述信息
 *
 * @author zgx
 * @version 1.0
 * @date 2025/10/15 11:46
 */
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public ApiResponse getCategories(Integer type) {
        try {
            List<Category> categories;

            if (type != null) {
                // 使用Lambda条件构造器
                LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Category::getType, type)
                        .orderByAsc(Category::getSort)
                        .orderByAsc(Category::getId);
                categories = list(wrapper);
            } else {
                // 查询所有，按排序字段和ID排序
                LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
                wrapper.orderByAsc(Category::getSort)
                        .orderByAsc(Category::getId);
                categories = list(wrapper);
            }

            return ApiResponse.success("获取分类成功", categories);
        } catch (Exception e) {
            return ApiResponse.error("获取分类失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse getCategoryDetail(Long id) {
        try {
            // 使用MyBatis-Plus的getById方法
            Category category = getById(id);

            if (category == null) {
                return ApiResponse.error("分类不存在");
            }

            return ApiResponse.success("获取分类详情成功", category);
        } catch (Exception e) {
            return ApiResponse.error("获取分类详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse addCategory(Category category) {
        try {
            // 检查分类名称是否已存在（同一类型下）
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getName, category.getName())
                    .eq(Category::getType, category.getType());

            boolean exists = count(wrapper) > 0;
            if (exists) {
                return ApiResponse.error("该分类名称已存在");
            }

            // 设置创建和更新时间
            category.setCreateTime(LocalDateTime.now());
            category.setUpdateTime(LocalDateTime.now());

            // 使用MyBatis-Plus的save方法
            boolean success = save(category);
            if (success) {
                Category newCategory = getById(category.getId());
                return ApiResponse.success("添加分类成功", newCategory);
            } else {
                return ApiResponse.error("添加分类失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("添加分类失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse updateCategory(Long id, Category category) {
        try {
            // 检查分类是否存在
            Category existingCategory = getById(id);
            if (existingCategory == null) {
                return ApiResponse.error("分类不存在");
            }

            // 检查分类名称是否已被其他分类使用
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Category::getName, category.getName())
                    .eq(Category::getType, category.getType())
                    .ne(Category::getId, id); // 排除当前分类

            boolean exists = count(wrapper) > 0;
            if (exists) {
                return ApiResponse.error("该分类名称已存在");
            }

            category.setId(id);
            category.setUpdateTime(LocalDateTime.now());

            // 使用MyBatis-Plus的updateById方法
            boolean success = updateById(category);
            if (success) {
                Category updatedCategory = getById(id);
                return ApiResponse.success("更新分类成功", updatedCategory);
            } else {
                return ApiResponse.error("更新分类失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("更新分类失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse deleteCategory(Long id) {
        try {
            Category category = getById(id);
            if (category == null) {
                return ApiResponse.error("分类不存在");
            }

            // 检查该分类是否被记账记录使用
            boolean isUsed = categoryMapper.existsRecordByCategoryId(id);
            if (isUsed) {
                return ApiResponse.error("该分类已被记账记录使用，无法删除");
            }

            // 使用MyBatis-Plus的removeById方法
            boolean success = removeById(id);
            if (success) {
                return ApiResponse.success("删除分类成功");
            } else {
                return ApiResponse.error("删除分类失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("删除分类失败: " + e.getMessage());
        }
    }

//    @Override
//    public ApiResponse getCategoriesByType(Integer type) {
//        try {
//            // 使用Lambda条件构造器的链式调用
//            List<Category> categories = lambdaQuery()
//                    .eq(type != null, Category::getType, type)
//                    .orderByAsc(Category::getSort)
//                    .orderByAsc(Category::getId)
//                    .list();
//
//            return ApiResponse.success("获取分类成功", categories);
//        } catch (Exception e) {
//            return ApiResponse.error("获取分类失败: " + e.getMessage());
//        }
//    }

    /**
     * 使用MyBatis-Plus的分页查询示例
     */
    public ApiResponse getCategoriesByPage(Integer page, Integer size, Integer type) {
        try {
            // 创建分页对象
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Category> pageInfo =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            // 创建查询条件
            LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(type != null, Category::getType, type)
                    .orderByAsc(Category::getSort)
                    .orderByAsc(Category::getId);

            // 执行分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Category> result = page(pageInfo, wrapper);

            return ApiResponse.success("获取分类成功", result);
        } catch (Exception e) {
            return ApiResponse.error("获取分类失败: " + e.getMessage());
        }
    }

    @Override
    public List<Category> getCategoryTree() {
        // 查询所有分类
        List<Category> allCategories = categoryMapper.selectAllWithTree();
        // 构建树形结构
        return buildCategoryTree(allCategories);
    }

    @Override
    public List<Category> getCategoryTreeByType(Integer type) {
        // 查询指定类型的分类
        List<Category> categoriesByType = categoryMapper.selectByType(type);
        // 构建树形结构
        return buildCategoryTree(categoriesByType);
    }

    @Override
    public List<Category> buildCategoryTree(List<Category> categories) {
        if (categories == null || categories.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取所有顶级分类（parentId = 0）
        List<Category> rootCategories = categories.stream()
                .filter(category -> category.getParentId() == 0)
                .sorted((c1, c2) -> {
                    int sortCompare = c1.getSort().compareTo(c2.getSort());
                    return sortCompare != 0 ? sortCompare : c1.getId().compareTo(c2.getId());
                })
                .collect(Collectors.toList());

        // 为每个顶级分类设置子分类
        for (Category rootCategory : rootCategories) {
            rootCategory.setChildren(getChildren(rootCategory, categories));
        }

        return rootCategories;
    }

    /**
     * 递归获取子分类
     */
    private List<Category> getChildren(Category parent, List<Category> allCategories) {
        List<Category> children = allCategories.stream()
                .filter(category -> parent.getId().equals(category.getParentId()))
                .sorted((c1, c2) -> {
                    int sortCompare = c1.getSort().compareTo(c2.getSort());
                    return sortCompare != 0 ? sortCompare : c1.getId().compareTo(c2.getId());
                })
                .collect(Collectors.toList());

        // 递归设置子分类的子分类
        for (Category child : children) {
            child.setChildren(getChildren(child, allCategories));
        }

        return children;
    }

    /**
     * 批量删除分类
     */
    @Transactional
    public ApiResponse deleteBatchCategories(List<Long> ids) {
        try {
            // 检查是否有分类被使用
            for (Long id : ids) {
                boolean isUsed = categoryMapper.existsRecordByCategoryId(id);
                if (isUsed) {
                    return ApiResponse.error("ID为 " + id + " 的分类已被记账记录使用，无法删除");
                }
            }

            // 使用MyBatis-Plus的removeByIds方法进行批量删除
            boolean success = removeByIds(ids);
            if (success) {
                return ApiResponse.success("批量删除分类成功");
            } else {
                return ApiResponse.error("批量删除分类失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("批量删除分类失败: " + e.getMessage());
        }
    }
}
